/**
 * Created by BIYY on 2017-11-17.
 */
//import {Loading, Message} from 'element-ui';
import {showNotify, showLoadingToast,closeToast} from 'vant';

import axios from 'axios';
import config from '../../config/index';
import urlUtil from '../url/index';

const request:any = {};

/**
 * ajax请求失败
 * @param msg
 * @param timeOut
 * @param locate
 * @param opt
 */
request.ajaxError = (msg:any, timeOut:any, locate:any, opt:any) => {
    if (msg) {
        setTimeout(() => {
            if (typeof msg === 'string') {
                showNotify({ type: 'danger', message:msg});
            } else {
                showNotify({ type: 'danger', message:JSON.stringify(msg)});
            }
        }, 20);
    } else {
        showNotify({ type: 'danger', message:opt.api.url + "网络异常!"});
    }
    closeToast();
    clearTimeout(timeOut);
};
/**
 * ajax
 * @param opt
 * @param locate
 * @returns {Promise<unknown>|boolean}
 */
request.ajax = (opt:any, locate:any = 'zh_CN') => {
    let option:any = {};
    const setTime:any = {};
    const time = new Date().valueOf();
    const showLoading = opt.api.showLoading; //是否出現loading
    let loadingTime = 2000; //出现loading时间
    const method = opt.api.method || config.requestType.get;
    const url = opt.api.url;
    const headers = opt.headers || opt.api.headers || {};
    if (!url) {
        request.ajaxError('链接不能为空！', setTime[time], locate, opt);
        return false;
    }
    if (opt.api && opt.api.loadingTime) {
        loadingTime = opt.api.loadingTime;
    }
    setTime[time] = setTimeout(() => { // 超过一定時間后出现加载条
        if (showLoading !== false) {
            showLoadingToast({
                className:'vant-loading',
                message: '加载中...',
                forbidClick: true,
                duration: 0
            });
        }
    }, loadingTime);
    option.headers = headers;
    option.method = method;
    option.url = url;
    if (opt.api && opt.api.inject) { //自定义注入器
        option = opt.api.inject(option);
    }
    if (method === config.requestType.get) { //get请求
        if (opt.data) {
            opt.data.ver = new Date().valueOf();
            option.params = opt.data;
        }
    } else { //post请求
        if (opt.data) {
            opt.data.ver = new Date().valueOf();
            option.data = opt.data;
        }
        if (opt.api.form) {
            const params = new URLSearchParams();
            Object.keys(opt.data).forEach((key) => {
                params.append(key, opt.data[key]);
            });
            option.data = params;
        }
    }
    option.params = option.params || opt.params || {};
    option.timeout = opt.timeout || opt.api.timeout || 0; // default is `0` (no timeout)
    if (opt.api.download) {
        opt.data.token = option.headers.token
        location.href = urlUtil.urlEncode(opt.api.url, opt.data,null,null)
        closeToast();
        clearTimeout(setTime[time]);
        return;
    }
    return new Promise((resolve, reject) => {
        axios(option)
            .then((response) => {
                request.render(response, opt, setTime, time, resolve, locate);
                closeToast();
                clearTimeout(setTime[time]);
            }).catch((error) => {
            const response = error.response;
            request.render(response, opt, setTime, time, resolve, locate);
            closeToast();
            clearTimeout(setTime[time]);
            opt.errorCallBack instanceof Function && opt.errorCallBack(response);
        });
    });
};
/**
 * 处理 ajax返回
 * @param response
 * @param opt
 * @param setTime
 * @param time
 * @param resolve
 * @param locate
 */
request.render = (response:any, opt:any, setTime:any, time:any, resolve:any, locate:any) => {
    if (response) {
        if (opt.api && opt.api.intercept) { //自定义状态码拦截器
            opt.api.intercept(response.data, resolve, (msg:any) => {
                opt.errorCallBack instanceof Function && opt.errorCallBack(msg);
                request.ajaxError(msg, setTime[time], locate, opt);
            });
        } else if (response.status === 503 || response.status === 500 || response.status === 504 || response.status === 400) {
            opt.errorCallBack instanceof Function && opt.errorCallBack(response.statusText);
            request.ajaxError(response.statusText, setTime[time], locate, opt);
        } else {
            resolve(response.data);
        }
    } else {
        opt.errorCallBack instanceof Function && opt.errorCallBack("网络异常!");
        request.ajaxError(opt.api.url + "网络异常!", setTime[time], locate, opt);
    }
};
export default request;
